package com.lw.common.exception

import android.net.ParseException
import android.view.View
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import kotlinx.coroutines.CoroutineExceptionHandler
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException


object HandleException {

    private var mExceptionListener: ExceptionListener? = null

    fun setListener(listener: ExceptionListener) = apply {
        this.mExceptionListener = listener
    }

    /**
     * 异常统一处理
     */
    fun handleException(e: Throwable): ResponseException {
        val ex: ResponseException
        when (e) {
            is ResponseException -> {
                ex = e
            }
            is HttpException -> {
                ex = ResponseException(ErrorCode.HTTP_ERROR, e)
            }
            is JsonParseException, is JSONException, is ParseException, is MalformedJsonException -> {
                ex = ResponseException(ErrorCode.PARSE_ERROR, e)
            }
            is ConnectException -> {
                ex = ResponseException(ErrorCode.NETWORK_ERROR, e)
            }
            is javax.net.ssl.SSLException -> {
                ex = ResponseException(ErrorCode.SSL_ERROR, e)
            }
            is java.net.SocketTimeoutException -> {
                ex = ResponseException(ErrorCode.TIMEOUT_ERROR, e)
            }
            is java.net.UnknownHostException -> {
                ex = ResponseException(ErrorCode.TIMEOUT_ERROR, e)
            }
            else -> {
                ex = if (!e.message.isNullOrEmpty()) {
                    ResponseException(1000, e.message!!, e)
                } else {
                    ResponseException(ErrorCode.UNKNOWN, e)
                }
            }
        }
        mExceptionListener?.invoke(ex)
        return ex
    }
}

typealias ExceptionListener = (e: ResponseException) -> Unit
